package pe.edu.upla.lamerced.action;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import org.springframework.beans.factory.annotation.Autowired;

import pe.edu.upla.lamerced.bean.Detallefactura;
import pe.edu.upla.lamerced.bean.Detservicios;
import pe.edu.upla.lamerced.bean.Factura;
import pe.edu.upla.lamerced.bean.Habitacion;
import pe.edu.upla.lamerced.bean.Hospedaje;
import pe.edu.upla.lamerced.bean.Servicios;
import pe.edu.upla.lamerced.bean.Tipotarificacion;
import pe.edu.upla.lamerced.service.HabitacionService;
import pe.edu.upla.lamerced.service.HospedajeService;
import pe.edu.upla.lamerced.service.ServiciosService;
import pe.edu.upla.lamerced.utiles.Utiles;

public class ProcesosAction extends DispatchAction {

	private static final Logger logger = Logger.getLogger(ProcesosAction.class);
	
	@Autowired	
	ServiciosService serviciosService;
	
	@Autowired
	HabitacionService habitacionService;
	
	@Autowired
	HospedajeService hospedajeService;
	
	public ActionForward listaServicios(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" LISTA SERVICIOS ");
            request.setAttribute("lstServicios", serviciosService.listaServicios());            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("procesosHome");
		}
		return mapping.findForward("listaServicios");
	}
	
	public ActionForward preNuevoServ(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" PRE NUEVO SERVICIO");
            //request.setAttribute("lstCategorias", serviciosService.listaTipoTarificacion());
            request.setAttribute("lstTarificacion", serviciosService.listaTipoTarificacion());            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("procesosHome");
		}
		return mapping.findForward("nuevo");
	}
	
	public ActionForward preEditServ(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" PRE EDIT SERVICIO");
            String cod = request.getParameter("cod");
            Servicios ser = serviciosService.obtenerServicio(Integer.parseInt(cod));
            DynaActionForm myform = (DynaActionForm)form;
            myform.set("idservicios", ser.getIdservicios().toString());
            myform.set("nombre", ser.getNombre());
            myform.set("detalle", ser.getDetalle());
            myform.set("tarifa", ser.getTarifa().toString());
            myform.set("tarificacion", ser.getTipotarificacion().getIdtarificacion()+"");
            request.setAttribute("lstTarificacion", serviciosService.listaTipoTarificacion());
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("procesosHome");
		}
		return mapping.findForward("nuevo");
	}
	
	public ActionForward nuevoServ(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
			DynaActionForm myform = (DynaActionForm)form;
			
			Servicios ser = new Servicios();
			ser.setNombre(myform.getString("nombre"));
			ser.setDetalle(myform.getString("detalle"));
			ser.setTarifa(new Long(myform.getString("tarifa")));
			Tipotarificacion tt = new Tipotarificacion();
			tt.setIdtarificacion(Integer.parseInt(myform.getString("tarificacion")));
			ser.setTipotarificacion(tt);
			if(!Utiles.nullToBlank(myform.getString("idservicios")).equals("")){
				ser.setIdservicios(Integer.parseInt(myform.getString("idservicios")));
			}			
			logger.debug(ser.toString());
			serviciosService.registrarServicio(ser);
			ser = serviciosService.obtenerServicio(ser.getIdservicios());			
			request.setAttribute("nser",ser);
			request.setAttribute("mensaje", "nuevo servicio registrado");
            logger.debug(" NUEVO SERVICIO RALIZADA");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            request.setAttribute("lstTarificacion", serviciosService.listaTipoTarificacion());
            return mapping.findForward("nuevo");
		}
		return mapping.findForward("confirmar");
	}
	
	public ActionForward cancelNuevoServ(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" cancelacion SERVICIO RALIZADA");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
		}
		return mapping.findForward("procesosHome");
	}
	
	public ActionForward viewServ(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
			String cod = request.getParameter("cod");
            request.setAttribute("nser", serviciosService.obtenerServicio(Integer.parseInt(cod)));            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("procesosHome");
		}
		return mapping.findForward("confirmar");
	}
	
	public ActionForward preVenderServ(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" PRE VENTA SERVICIOS ");
            request.setAttribute("lsthospedaje",hospedajeService.listaHospedajesActivos());
            request.setAttribute("lstServicios", serviciosService.listaServicios());
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("home");
		}
		return mapping.findForward("seleccionar");
	}
	
	public ActionForward venderServ(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" VENTA DE SERVICIOS ");
            DynaActionForm myform = (DynaActionForm)form;
            Detservicios venta = new Detservicios();            
            //venta.setHospedaje( hospedajeService.obtenerHospedaje(Integer.parseInt(myform.getString("habitacion"))));
            venta.setHospedaje(new Hospedaje(Integer.parseInt(myform.getString("idhospedaje"))));
            venta.setServicios(new Servicios(Integer.parseInt(myform.getString("idservicios"))));
            venta.setCantidad(Integer.parseInt(myform.getString("cantidad")));
            serviciosService.registrarVentaServicio(venta);
            request.setAttribute("mensaje", "servicio agregado al huesped");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("seleccionar");
		}
		return mapping.findForward("procesosHome");
	}
	
	public ActionForward preFactura(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" pre generar factura ");
            String cod = request.getParameter("cod");
            Hospedaje hos =  hospedajeService.obtenerHospedaje(Integer.parseInt(cod));
           	hos.setEstado(3);
           	hos.getHabitacion().setEstado(0);
           	hos.setFecSalida(new Date());
           	
           	Calendar cal = new GregorianCalendar();
           	cal.setTime(hos.getFecAlquiler());
           	
           	Calendar cal2 = new GregorianCalendar();
           	cal2.setTime(hos.getFecSalida());
           	int dias = cal.get(Calendar.DAY_OF_YEAR);
           	int dias2 = cal2.get(Calendar.DAY_OF_YEAR);
           	
           	hos.setDiasreserva(dias2 - dias);
           	
           	logger.debug("d"+ hos.getDiasreserva());
           	List<Detservicios> lis = serviciosService.listarServicioHospedaje(hos.getIdhospedaje());
           	
           	//TODO crear factura y detalle de factura con monto calculado
           	Factura fac = new Factura();
           	fac.setHospedaje(hos);
           	fac.setFecha(new Date());
           	//fac.setDetallefacturas(detallefacturas)
           	List<Detallefactura> lisDet = new ArrayList<Detallefactura>();
           	double monto = hos.getHabitacion().getPrecioBase();
           	for(Detservicios det : lis){
           		lisDet.add(new Detallefactura(fac,det, new Long( det.getServicios().getTarifa() *  det.getCantidad() )));
           		monto = monto + (det.getServicios().getTarifa() *  det.getCantidad());
           	}
           	fac.setMontoBruto(monto);
           	fac.setIgv( monto * 0.19 );
           	fac.setMontoNeto( monto + fac.getIgv() );
           	
           	//request.setAttribute("lstServi", lis);
           	request.getSession().setAttribute("lstServi", lisDet);
           	request.getSession().setAttribute("hospfac", fac);
           	
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("reserva");
		}
		return mapping.findForward("procesapago");
	}
	@SuppressWarnings("unchecked")
	public ActionForward factura(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" PRE GENERAR FACTURA ");
        	Factura fac = (Factura)request.getSession().getAttribute("hospfac");
           	List<Detallefactura> lisDet = (List<Detallefactura>)request.getSession().getAttribute("lstServi");
            hospedajeService.registrarFactura(fac,lisDet);
            
            request.setAttribute("dfact", fac);
            request.setAttribute("lstServi", lisDet);
            request.setAttribute("mensaje", "Factura registrda en elsistema");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("reserva");
		}
		return mapping.findForward("confirmarpago");
	}
	
	public ActionForward verHospedaje(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)	throws Exception {
		try {
            logger.debug(" vista acutal de factura");
            logger.debug(" pre generar factura ");
            String cod = request.getParameter("cod");
            Hospedaje hos =  hospedajeService.obtenerHospedaje(Integer.parseInt(cod));
           	hos.setEstado(3);
           	hos.getHabitacion().setEstado(0);
           	hos.setFecSalida(new Date());
           	
           	Calendar cal = new GregorianCalendar();
           	cal.setTime(hos.getFecAlquiler());
           	
           	Calendar cal2 = new GregorianCalendar();
           	cal2.setTime(hos.getFecSalida());
           	int dias = cal.get(Calendar.DAY_OF_YEAR);
           	int dias2 = cal2.get(Calendar.DAY_OF_YEAR);
           	
           	hos.setDiasreserva(dias2 - dias);
           	
           	logger.debug("d"+ hos.getDiasreserva());
           	List<Detservicios> lis = serviciosService.listarServicioHospedaje(hos.getIdhospedaje());
           	
           	//TODO crear factura y detalle de factura con monto calculado
           	Factura fac = new Factura();
           	fac.setHospedaje(hos);
           	fac.setFecha(new Date());
           	//fac.setDetallefacturas(detallefacturas)
           	List<Detallefactura> lisDet = new ArrayList<Detallefactura>();
           	double monto = hos.getHabitacion().getPrecioBase();
           	for(Detservicios det : lis){
           		lisDet.add(new Detallefactura(fac,det, new Long( det.getServicios().getTarifa() *  det.getCantidad() )));
           		monto = monto + (det.getServicios().getTarifa() *  det.getCantidad());
           	}
           	fac.setMontoBruto(monto);
           	fac.setIgv( monto * 0.19 );
           	fac.setMontoNeto( monto + fac.getIgv() );
           	
           	request.setAttribute("lstServi", lisDet);
           	request.setAttribute("dfact", fac);
           	
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msgError", e.getMessage());
            return mapping.findForward("reserva");
		}
		return mapping.findForward("confirmarpago");
	}
	
	
	
}